//某店铺将用于组成套餐的商品记作字符串 goods，其中 goods[i] 表示对应商品。请返回该套餐内所含商品的 全部排列方式 。 
//
// 返回结果 无顺序要求，但不能含有重复的元素。 
//
// 
//
// 示例 1： 
//
// 
//输入：goods = "agew"
//输出：["aegw","aewg","agew","agwe","aweg","awge","eagw","eawg","egaw","egwa",
//"ewag","ewga","gaew","gawe","geaw","gewa","gwae","gwea","waeg","wage","weag","wega",
//"wgae","wgea"]
// 
//
// 
//
// 提示： 
//
// 
// 1 <= goods.length <= 8 
// 
//
// 
//
// Related Topics 字符串 回溯 👍 730 👎 0


package LeetCode.editor.cn;


import java.util.*;

/**
 * @author ldltd
 * @date 2025-05-14 10:15:22
 * @description LCR 157.套餐内商品的排列顺序
 
 */
 
public class ZiFuChuanDePaiLieLcof {
    public static void main(String[] args) {
    //测试代码
    ZiFuChuanDePaiLieLcof fun = new ZiFuChuanDePaiLieLcof();
    Solution solution= fun.new Solution();
    
    }

//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
    public String[] goodsOrder(String goods) {
        List<String> list = new ArrayList<>();
        if (goods == null || goods.isEmpty()) {
            return new String[0];
        }
        char[] chars = goods.toCharArray();
        Arrays.sort(chars); // 排序以便去重
        dfs(new StringBuilder(), new boolean[chars.length], chars, list);
        return list.toArray(new String[0]);
    }
    private void dfs(StringBuilder sb, boolean[] visited, char[] chars, List<String> list) {
        if (sb.length() == chars.length) {
            list.add(sb.toString());
            return;
        }
        for (int i = 0; i < chars.length; i++) {
            if (visited[i]) continue; // 该位置的字符已被使用，跳过
            if (i > 0 && chars[i] == chars[i - 1] && !visited[i - 1]) continue; // 去重逻辑
            sb.append(chars[i]);
            visited[i] = true;
            dfs(sb, visited, chars, list);
            sb.deleteCharAt(sb.length() - 1);
            visited[i] = false;
        }
    }

}
//leetcode submit region end(Prohibit modification and deletion)

}
